package whf.framework.config;

import java.net.URL;
import java.util.Map;

import whf.framework.util.ExpireableMap;

/**
 * @author wanghaifeng
 *
 */
public class ConfigurationFactory {
	private Map<Object, Configuration> configurations;
	
	private static ConfigurationFactory instance = new ConfigurationFactory();
	
	public static ConfigurationFactory getInstance(){
		return instance;
	}
	
	private ConfigurationFactory(){
		this.configurations = new ExpireableMap<Object, Configuration>(1000*60*10);
	}
	
	public Configuration getConfiguration(Object config) throws ConfigurationException{
		Configuration cfg = configurations.get(config);
		if(cfg == null){
			cfg = this.buildConfigurations(config);
			configurations.put(config, cfg);
		}
		return cfg;
	}
	
	private synchronized Configuration buildConfigurations(Object configs) throws ConfigurationException{
		if(configs instanceof String){
			String config = configs.toString();
			if(config.toLowerCase().endsWith("xml")){
				return new XmlConfiguration(config);
			} else if(config.toLowerCase().endsWith("properties")){
				return new PropertiesConfiguration(config);
			}
		} else if(configs instanceof URL){
			String config = configs.toString();
			URL url = (URL)configs;
			if(config.toLowerCase().endsWith("xml")){
				return new XmlConfiguration(url);
			} else if(config.toLowerCase().endsWith("properties")){
				return new PropertiesConfiguration(url);
			}
		}
		return null;
	}
}
